/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.attendancerecord.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.IpAddressUtil;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.facedoor.modular.memberuser.vo.MemberUserPageVO;
import vip.xiaonuo.modular.attendancerecord.entity.AttendanceRecord;
import vip.xiaonuo.modular.attendancerecord.enums.AttendanceRecordExceptionEnum;
import vip.xiaonuo.modular.attendancerecord.mapper.AttendanceRecordMapper;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceRecordBatchEditParam;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceRecordParam;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceRecordQueryParam;
import vip.xiaonuo.modular.attendancerecord.service.AttendanceRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.attendancerecord.vo.AttendanceRecordSummary;
import vip.xiaonuo.modular.attendancerecord.vo.AttendanceRecordVo;
import vip.xiaonuo.modular.attendanceshift.entity.AttendanceShift;
import vip.xiaonuo.modular.attendanceshift.service.AttendanceShiftService;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 考勤记录service接口实现类
 *
 * @author JOE
 * @date 2022-11-15 17:14:13
 */
@Service
public class AttendanceRecordServiceImpl extends ServiceImpl<AttendanceRecordMapper, AttendanceRecord> implements AttendanceRecordService {

    @Resource
    private AttendanceRecordMapper recordMapper;

    @Resource
    private AttendanceShiftService shiftService;

    @Override
    public PageResult<AttendanceRecord> page(AttendanceRecordParam attendanceRecordParam) {
        QueryWrapper<AttendanceRecord> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(attendanceRecordParam)) {

            // 根据用户 查询
            if (ObjectUtil.isNotEmpty(attendanceRecordParam.getMemberUserId())) {
                queryWrapper.lambda().eq(AttendanceRecord::getMemberUserId, attendanceRecordParam.getMemberUserId());
            }
            // 根据班次 查询
            if (ObjectUtil.isNotEmpty(attendanceRecordParam.getAttendanceShiftId())) {
                queryWrapper.lambda().eq(AttendanceRecord::getAttendanceShiftId, attendanceRecordParam.getAttendanceShiftId());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public PageResult<AttendanceRecordVo> findPage(AttendanceRecordQueryParam param) {
        return new PageResult<>(recordMapper.findPage(PageFactory.defaultPage(), param));
    }

    @Override
    public List<AttendanceRecord> list(AttendanceRecordParam attendanceRecordParam) {
        return this.list();
    }

    @Override
    public void add(AttendanceRecordParam attendanceRecordParam) {
        AttendanceRecord attendanceRecord = new AttendanceRecord();
        BeanUtil.copyProperties(attendanceRecordParam, attendanceRecord);
        this.save(attendanceRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(AttendanceRecordParam attendanceRecordParam) {
        this.removeById(attendanceRecordParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AttendanceRecordParam attendanceRecordParam) {
        AttendanceRecord attendanceRecord = this.queryAttendanceRecord(attendanceRecordParam);
        BeanUtil.copyProperties(attendanceRecordParam, attendanceRecord);
        this.judgeAttendanceRecordStatus(attendanceRecord,false);
        this.updateById(attendanceRecord);
    }

    @Override
    public AttendanceRecord detail(AttendanceRecordParam attendanceRecordParam) {
        return this.queryAttendanceRecord(attendanceRecordParam);
    }

    @Override
    public PageResult<AttendanceRecordSummary> summary(AttendanceRecordQueryParam param) {
        return new PageResult<>(recordMapper.summaryRecord(PageFactory.defaultPage(), param));
    }

    @Override
    public void export(AttendanceRecordQueryParam param) {
        List<AttendanceRecordSummary> summaries = recordMapper.summaryExport(param);
        PoiUtil.exportExcelWithStream("考勤汇总.xls", AttendanceRecordSummary.class, summaries);
    }

    @Override
    public void batchUpdate(AttendanceRecordBatchEditParam param) {
        List<AttendanceRecord> records = this.listByIds(param.getRow());
        int type = param.getType();
        String date_str = param.getDate();
        Date date;
        try {
            date = DateUtils.parseDate(date_str,"yyyy-MM-dd HH:mm");
        } catch (ParseException e) {
            throw new ServiceException(500,"时间转换异常");
        }
        for(AttendanceRecord record : records){
            if(type==1){ // 上班打卡
                record.setClockInTime(date);
            }else if(type == 2){ // 下班打卡
                record.setClockOutTime(date);
            }
            this.judgeAttendanceRecordStatus(record,true);
        }
        this.saveOrUpdateBatch(records);
    }

    /**
     * 获取考勤记录
     *
     * @author JOE
     * @date 2022-11-15 17:14:13
     */
    private AttendanceRecord queryAttendanceRecord(AttendanceRecordParam attendanceRecordParam) {
        AttendanceRecord attendanceRecord = this.getById(attendanceRecordParam.getId());
        if (ObjectUtil.isNull(attendanceRecord)) {
            throw new ServiceException(AttendanceRecordExceptionEnum.NOT_EXIST);
        }
        return attendanceRecord;
    }

    // TODO
    public void judgeAttendanceRecordStatus( AttendanceRecord record,boolean isBatch){
        Long shiftId = record.getAttendanceShiftId();
        AttendanceShift shift = shiftService.getById(shiftId);
        if(shift==null){
            return;
        }

        // 判断是否迟到
        judgeIsLate(record,shift);

        // 判断是否早退
        judgeIsLeaveEarly(record);

        // 判断是否缺勤
        if(isBatch){
            judgeIsAbsenceDuty(record);
        }

        if(record.getIsAbsenceDuty()!=2){
            record.setLeaveReason(null);
        }

        // 计算工作时长
        calcWorkTime(record);

    }




    /**
     * 是否迟到
     * @param record
     * @param shift
     */
    private void judgeIsLate(AttendanceRecord record, AttendanceShift shift) {
        int lateTime = shift.getLateMinutes();
        int isLate ;
        if(lateTime < 0 || record.getClockInTime()==null){
            isLate = 0;
        }else{
            Calendar clockInTime = Calendar.getInstance();
            clockInTime.setTime(record.getClockInTime());

            Calendar deadLine = Calendar.getInstance();
            deadLine.setTime(record.getStartDate());
            deadLine.add(Calendar.MINUTE, lateTime);

            isLate = clockInTime.after(deadLine) ? 1 : 0;
        }
        record.setIsLate(isLate);
    }

    /**
     * 判断是否早退
     * @param record
     */
    private void judgeIsLeaveEarly(AttendanceRecord record) {
        if(record.getClockOutTime()!=null){
            Calendar clockOutTime = Calendar.getInstance(); // 下班打卡时间
            clockOutTime.setTime(record.getClockOutTime());

            Calendar endTime = Calendar.getInstance();      // 下班时间
            endTime.setTime(record.getEndDate());

            record.setIsLeaveEarly(clockOutTime.before(endTime) ? 1 : 0);
        }
    }

    /**
     * 判断是否缺勤
     * @param record
     */
    private void judgeIsAbsenceDuty(AttendanceRecord record) {
        if(record.getIsAbsenceDuty()!=2){
            if(record.getClockInTime()==null && record.getClockOutTime()==null){
                record.setIsAbsenceDuty(1);
            }else{
                record.setIsAbsenceDuty(0);
            }
        }
    }

    /**
     * 计算工作时长
     * @param record
     */
    private void calcWorkTime(AttendanceRecord record) {
        if(record.getClockInTime()!=null && record.getClockOutTime()!=null){
            // 获取小时
            double hours = this.getDistanceOfTwoDate(record.getClockInTime(),record.getClockOutTime());
            record.setWorkTime(hours);
        }else{
            record.setWorkTime(null);
        }
    }

    /**
     * 获取两个时间点之间的小时数
     * @param before
     * @param after
     * @return
     */
    private double getDistanceOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        BigDecimal diff_ms = new BigDecimal(afterTime).subtract(new BigDecimal(beforeTime));

        BigDecimal hours = diff_ms.divide(new BigDecimal("3600000" ),2,BigDecimal.ROUND_HALF_UP);

        return hours.doubleValue();
    }


}
